package com.example.okhttp.util

import com.example.okhttp.BuildConfig
import com.example.okhttp.data.EncryptedRequest
import com.example.okhttp.data.EncryptedResponse
import com.example.okhttp.test.TEST_RN_KEY_HEAD
import com.example.okhttp.test.TEST_RN_KEY_HEAD_NA
import com.example.okhttp.test.TEST_RN_KEY_PARAM
import com.example.okhttp.test.TEST_RN_KEY_PKG
import com.example.okhttp.test.TEST_RN_KEY_VERSION
import com.google.gson.Gson
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.Response
import okhttp3.ResponseBody
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Converter


// 请求头拦截器
class HeaderInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val headers = mapOf(
            "sourceChannel" to "Orange",
            "packageName" to TEST_RN_KEY_PKG,
            "version" to TEST_RN_KEY_VERSION,
            "adid" to "",
            "uuId" to "",
            "userId" to ""
        )
        val headersJson = Gson().toJson(headers)
        printDe("HeaderInterceptor$headersJson")
        // 添加加密的安全头
        val encryptedHeader = AESUtils2.encrypt(headersJson, TEST_RN_KEY_HEAD)
        printDe("HeaderInterceptor$encryptedHeader")

        val fixLn = encryptedHeader.replace("[\n\r]".toRegex(), "")
        printDe("HeaderInterceptor$fixLn")

        val originalRequest = chain.request()
        val newRequest = originalRequest.newBuilder().build()
        return chain.proceed(
            newRequest.newBuilder()
                .header(TEST_RN_KEY_HEAD_NA, fixLn)
                .build()
        )
    }
}

// 请求加密转换器
class EncryptionConverter : Converter<EncryptedRequest, RequestBody> {
    override fun convert(value: EncryptedRequest): RequestBody {
        // 1. 将原始数据转换为JSON
        val json = value.data
        printDe("EncryptionConverter$json")

        // 2. 加密数据
        val encrypted = AESUtils2.encrypt(json, TEST_RN_KEY_PARAM)//CryptoUtils.encrypt(json)
        printDe("EncryptionConverter$encrypted")

        // 3. 创建加密后的请求体
        return RequestBody.create(
            "application/json".toMediaTypeOrNull(),
            Gson().toJson(EncryptedRequest(encrypted))
        )
    }
}

// 响应解密转换器
class DecryptionConverter : Converter<ResponseBody, EncryptedResponse?> {
    override fun convert(value: ResponseBody): EncryptedResponse? {
        val response = value.string()
        printDe("DecryptionConverter 解密前 $response")
        if (response.isEmpty()) return EncryptedResponse(response)

        val decryptedJson = AESUtils2.decrypt(
            response,
            TEST_RN_KEY_PARAM
        )//CryptoUtils.decrypt(encryptedResponse.encryptedData)
        printDe("DecryptionConverter 解密后 $decryptedJson")
        if (decryptedJson == null) return null

        return EncryptedResponse(decryptedJson)
    }
}

fun createLogInterceptor(): HttpLoggingInterceptor {
    val mLog = HttpLoggingInterceptor { _ ->
        //printDe("HttpLoggingInterceptor$mes")
    }
    // 设置日志级别
    mLog.level =
        if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.NONE
    return mLog
}
